# coding=utf-8
import traceback
import requests
from datetime import timedelta
from monthdelta import monthdelta
from pymongo import MongoClient
from simplemysql import SimpleMysql
from datetime import datetime
from pandas import Series, DataFrame
import sys
import pandas as pd
import numpy as np
reload(sys)

def filter_period_indices(stock_period_df, day):
    all_period = stock_period_df.index
    for i in range(len(all_period)):
        period = all_period[i]
        if i == (len(all_period) - 1):
            '''
            比如现在是2018年7月1，目前只有1季度报表，半年报在2季度结束后2个月才有结果
            今天计算的财报数据还是以1季报为准，
            所以计算以哪个财报数据为准备？年报是3个月delay，半年报是2个月delay，季报以1个月delay
            '''
            delay = 0
            if period[4:6] == '03':
                delay = 5
            if period[4:6] == '09':
                delay = 6
            if period[4:6] == '06':
                delay = 4
            if period[4:6] == '12':
                delay = 4
            next_period = (datetime.strptime(period, '%Y%m%d') + monthdelta(delay)).strftime("%Y%m%d")
            if period <= day < next_period:
                return stock_period_df.iloc[i]
        else:
            next_period = all_period[i + 1]
            if period <= day < next_period:
                return stock_period_df.iloc[i+1]
    return None


def test_filter_period_indices():
    print(">>>CalcStockDailyK.filter_period_indices")
    df = pd.DataFrame([[-1, 4], [np.nan, 4], [0, 4], [2, 4], [5, 4], [6, 4], [7, 4], [8, 4]],
                      index=['20150331', '20150630', '20150931', '20151220', '20160331', '20160630', '20160931', '20161230'],
                      columns=['income', 'cost'])
    print df
    result = filter_period_indices(df, '20170401')
    assert result.name == '20161230'

test_filter_period_indices()